import Vue from 'vue'
var app = getApp();

const token = uni.getStorageSync('token');
class Upload {
  constructor(object) {
    this.obj = {
      count: 9,
      sizeType: ['original', 'compressed'],
      // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'] // 可以指定来源是相册还是相机，默认二者都有

    };

    if (Object.prototype.toString.call(object) === "[object Object]") {
         Object.assign(this.obj, object);
    } 
    return this;
  } 
  // 上传图片 返回一个图片的数组集合
  async uploadPic() {
    let chooseImageResult = await this.chooseImage();
    console.log("选择图片", chooseImageResult);
    let imgArr = await chooseImageResult.tempFilePaths.map(async (item, index) => {
      uni.showLoading({
        title: `正在上传第${index + 1}张`
      });
      let uploadFileResult = await this.uploadFile(item);
      console.log("上传图片过程", uploadFileResult);
      console.log(uploadFileResult);
      return  uploadFileResult.data;
    });
    return new Promise((resolve, reject) => {
      Promise.all(imgArr).then(result => {
        uni.hideLoading();
        uni.showToast({
          title: '上传成功',
          icon: "none",
          duration: 2000
        });
        console.log("上传图片结果", result);
        resolve(result);
      });
    });
  }

  uploadFile(file) {
	let base_url = Vue.prototype.uploadFileurl
    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: base_url,
        //此处是你自己上传接口
        filePath: file,
        method: 'POST',
        name: "file",
		header:{
			'Authorization': token
		},
        success: function (res) {
          var data =  res.data;
		  let imgdata = JSON.parse(res.data)
          resolve(imgdata);
        },
        fail: function (res) {
          reject("上传失败");
        },
        complete: function (res) {
          uni.hideToast();
        }
      });
    });
  }

  chooseImage() {
    return new Promise((resolve, reject) => {
      uni.chooseImage({
        count: this.obj.count,
        //1, // 默认9
        sizeType: this.obj.sizeType,
        //['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: this.obj.sourceType,
		
        //['album','camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          // console.log(res)
          resolve(res);
        },
        fail: function () {
          reject("选择文件失败");
        }
      });
    });
  }

}
const Uploads = new Upload();
export default Uploads